<?php
/**
 * Created by PhpStorm.
 * User: zhangxilu
 * Date: 2018/4/23
 * Time: 下午10:07
 */

namespace common\logic;


use common\models\CouponModel;
use yii\db\ActiveQuery;

class CouponLogic extends Logic
{

    /**
     * @return ActiveQuery
     */
    protected function _getActiveQuery()
    {
        return CouponModel::find();
    }

    /**
     * @param $id
     *
     * @return array|CouponModel
     */
    public function getById($id)
    {
        return $this->_get(['id' => $id]);
    }

    /**
     * 分页
     *
     * @param        $page
     * @param int    $pageSize
     * @param array  $search
     *
     * @return array
     */
    public function getByPage($page, $pageSize = 20, $search = [])
    {
        $nextPage = 0;
        $query = $this->_getActiveQuery();

        $offset = ($page - 1) * $pageSize;
        $query = $query->limit($pageSize + 1)->offset($offset)->orderBy(['id' => SORT_DESC]);


        $data = $query->asArray()->all();
        if (count($data) > $pageSize) {
            unset($data[$pageSize]);
            $nextPage = $page + 1;
        }
        $list = [];
        foreach ($data as $item) {
            $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
            $item['update_time'] = date('Y-m-d H:i:s', $item['update_time']);
            $list[] = $item;
        }

        return ['nextPage' => $nextPage, 'list' => $list];
    }
}